﻿using System;
using System.Collections.Generic;
using WickedFlame.Core.Shapes;
using WickedFlame.Core.State;

namespace WickedFlame.Core.History
{
    public class CutCommand : HistoryCommand
    {
        List<VectorShape> selectedShapes;
        Dictionary<VectorShape, ShapeMemento> originalStates;
        Dictionary<VectorShape, ShapeMemento> newStates;

        public CutCommand(List<VectorShape> shapelist, int layerIndex)
            : base(layerIndex)
        {
            Title = "Shape Cut";

            selectedShapes = shapelist;

            originalStates = new Dictionary<VectorShape,ShapeMemento>();

            foreach (VectorShape shape in selectedShapes)
            {
                if (shape is IStateCapturable)
                {
                    originalStates.Add(shape, ((IStateCapturable)shape).CreateMementoState());
                }
            }
        }

        /// <summary>
        /// sets the new state of the shapes in the selection list
        /// </summary>
        public void SetNewState()
        {
            newStates = new Dictionary<VectorShape, ShapeMemento>();
            
            foreach (VectorShape shape in selectedShapes)
            {
                if (shape is IStateCapturable)
                {
                    newStates.Add(shape, ((IStateCapturable)shape).CreateMementoState());
                }
            }
        }

        public override void Undo(ShapeList list)
        {
            foreach (VectorShape shape in selectedShapes)
            {
                if (originalStates.ContainsKey(shape))
                {
                    if (shape is IStateCapturable)
                    {
                        ((IStateCapturable)shape).ResetState(originalStates[shape]);
                    }
                }
            }
        }

        public override void Redo(ShapeList list)
        {
            foreach (VectorShape shape in selectedShapes)
            {
                if (newStates.ContainsKey(shape))
                {
                    if (shape is IStateCapturable)
                    {
                        ((IStateCapturable)shape).ResetState(newStates[shape]);
                    }
                }
            }
        }
    }
}
